﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using Aandelendelen.Db;

namespace Aandelendelen.Obs
{
	public class CommonQueries
	{
		public static void CancelAccount(int nawId)
		{
			QueryCollection queries = new QueryCollection();

			CommonQueries.CancelAccount(nawId, queries);

			queries.Execute();
		}

		public static void CancelAccount(int nawId, QueryCollection queries)
		{
			queries.Add(new Query("sp_cancelaccount", "Id", nawId, OleDbType.Integer));
			queries.Add(new Query("sp_updatereferrer", "RefId", nawId, OleDbType.Integer));
		}

		public static void InsertSaldoMutation(int nawId, decimal bedrag, int type, int fonds)
		{
			CommonQueries.InsertSaldoMutation(nawId, bedrag, type, fonds, 0, null);
		}

		public static void InsertSaldoMutation(int nawId, decimal bedrag, int type, int fonds, QueryCollection queries)
		{
			CommonQueries.InsertSaldoMutation(nawId, bedrag, type, fonds, 0, queries);
		}

		public static void InsertSaldoMutation(int nawId, decimal bedrag, int type, int fonds, int referralId)
		{
			CommonQueries.InsertSaldoMutation(nawId, bedrag, type, fonds, referralId, null);
		}

		public static void InsertSaldoMutation(int nawId, decimal bedrag, int type, int fonds, int referralId, QueryCollection queries)
		{
			if (type == 2) //try to cummulate deposits on the same day
			{
				QueryArguments cumArgs = new QueryArguments();

				cumArgs.Add("Bedrag", bedrag, OleDbType.Currency);
				cumArgs.Add("NawId", nawId, OleDbType.Integer);

				Query cumQuery = new Query("sp_updatesaldomutation", cumArgs);

				int numRows = (int)cumQuery.Execute();

				if (numRows == 1) //was this mutation added to an existing mutation? Then we're done. Else, insert a new mutation.
				{
					return;
				}
			}

			QueryArguments args = new QueryArguments();

			args.Add("NawId", nawId, OleDbType.Integer);
			args.Add("Bedrag", bedrag, OleDbType.Currency);
			args.Add("Type", type, OleDbType.Integer);
			args.Add("Fonds", fonds, OleDbType.Integer);
			args.Add("ReferralId", referralId, OleDbType.Integer);

			Query query = new Query("sp_insertsaldomutationnew", args);

			if (queries != null)
				queries.Add(query);
			else
				query.Execute();
		}

	}
}